package com.jasonzqshen.ifm.wizards;

import java.net.URI;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.internal.ide.dialogs.ProjectContentsLocationArea;
import org.eclipse.ui.internal.ide.dialogs.ProjectContentsLocationArea.IErrorMessageReporter;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;


import com.jasonzqshen.ifm.Plugin;
import com.jasonzqshen.ifm.PluginConfiguration;
import com.jasonzqshen.ifm.utils.SystemLog;

@SuppressWarnings("restriction")
public class NewProjectWizardPage extends WizardPage {

    private Text projectNameText;

    private ProjectContentsLocationArea locationArea;

    private Listener nameModifyListener = new Listener() {
        public void handleEvent(Event e) {
            dialogChanged();
        }
    };

    // constants
    private static final int SIZING_TEXT_FIELD_WIDTH = 250;


    /**
     * Constructor for New Project Wizard page
     */
    public NewProjectWizardPage() {
        super(PluginConfiguration.NEW_PROJECT_WIZARD_PAGE_ID);
        setTitle("Ifm feature modeling project file");
        setDescription("This wizard creates a new Ifm feature modeling project.");
        setPageComplete(false);
        SystemLog.logInfo("NewProjectWizardPage constructing complete");
    }

    @Override
    public void createControl(Composite parent) {
        // set create project wizard page layout
        Composite container = new Composite(parent, SWT.NULL);
        initializeDialogUnits(parent);
        GridLayout layout = new GridLayout();
        container.setLayout(layout);
        layout.numColumns = 1;
        layout.verticalSpacing = 9;

        createProjectNameGroup(container);
        locationArea = new ProjectContentsLocationArea(getErrorReporter(),
                container);
        setControl(container);

        SystemLog.logInfo("NewProjectWizardPage creating control complete");
    }

    /**
     * 
     * Get an error reporter for the receiver.
     * 
     * @return IErrorMessageReporter
     */
    private IErrorMessageReporter getErrorReporter() {
        return new IErrorMessageReporter() {
            /*
             * (non-Javadoc)
             * 
             * @see
             * 
             * org.eclipse.ui.internal.ide.dialogs.ProjectContentsLocationArea
             * 
             * .IErrorMessageReporter#reportError(java.lang.String)
             */
            public void reportError(String errorMessage, boolean infoOnly) {
                if (infoOnly) {
                    setMessage(errorMessage, IStatus.INFO);
                    setErrorMessage(null);
                } else
                    setErrorMessage(errorMessage);
                boolean valid = errorMessage == null;
                if (valid) {
                    dialogChanged();
                }
            }
        };
    }

    /**
     * Creates the project name specification controls.
     * 
     * @param parent
     *            the parent composite
     */
    private final void createProjectNameGroup(Composite parent) {
        // project specification group
        Composite projectGroup = new Composite(parent, SWT.NONE);
        GridLayout layout = new GridLayout();
        layout.numColumns = 2;
        projectGroup.setLayout(layout);
        projectGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

        // new project label
        Label projectLabel = new Label(projectGroup, SWT.NONE);
        projectLabel.setText("Project Name: ");
        projectLabel.setFont(parent.getFont());
        // new project name entry field
        projectNameText = new Text(projectGroup, SWT.BORDER);
        GridData data = new GridData(GridData.FILL_HORIZONTAL);
        data.widthHint = SIZING_TEXT_FIELD_WIDTH;
        projectNameText.setLayoutData(data);
        projectNameText.setFont(parent.getFont());
        // Set the initial value first before listener
        // to avoid handling an event during the creation.
        
        projectNameText.addListener(SWT.Modify, nameModifyListener);
    }

    /**
     * Ensure that both text fields are set as legal
     */
    private void dialogChanged() {
        String projName = getProjectName();
        IWorkspace workspace = Plugin.getPluginWorkspace();

        // check project name is empty
        if (projName.length() <= 0) {
            updateStatus("Project name must be specified");
            return;
        }

        // check project name contains illegal characters
        IStatus nameStatus = workspace
                .validateName(projName, IResource.PROJECT);
        if (!nameStatus.isOK()) {
            updateStatus(nameStatus.getMessage());
            return;
        }
        // check whether the project name exists

        IProject handle = ResourcesPlugin.getWorkspace().getRoot()
                .getProject(projName);
        if (handle.exists()) {
            updateStatus("A project with that name already exists in the workspace.");
            return;
        }
        
        String validLocationMessage = locationArea.checkValidLocation();
        if (validLocationMessage != null) { // there is no destination location
                                            // given
            updateStatus(validLocationMessage);
            return;
        }
        updateStatus(null);
    }
    

    /**
     * Update current page status
     * 
     * @param message
     */
    private void updateStatus(String message) {
        setErrorMessage(message);
        setPageComplete(message == null);
    }


    /**
     * Get project Name
     * 
     * @return
     */
    public String getProjectName() {
        if (projectNameText == null) {
            return ""; //$NON-NLS-1$
        }
        return projectNameText.getText().trim();
    }



    /**
     * Get Project Location
     * 
     * @return
     */
    public String getLocation() {
        return locationArea.getProjectLocation();
    }


    /**
     * Returns the current project location URI as entered by the user, or
     * <code>null</code> if a valid project location has not been entered.
     * 
     * @return the project location URI, or <code>null</code>
     * @since 3.2
     */
    public URI getLocationURI() {
        return locationArea.getProjectLocationURI();
    }


    /**
     * Returns the useDefaults.
     * 
     * @return boolean
     */
    public boolean useDefaults() {
        return locationArea.isDefault();
    }


}
